/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bakenote.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 *
 * @author lello
 */
public class ScaleImage {

	public static void saveScaleImage(String srcFile, int destWidth, int destHeight,
			String destFile) throws IOException {
		BufferedImage src = ImageIO.read(new File(srcFile));
		BufferedImage dest = new BufferedImage(destWidth, destHeight,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = dest.createGraphics();
		AffineTransform at = AffineTransform.getScaleInstance(
				(double) destWidth / src.getWidth(),
				(double) destHeight / src.getHeight());
		g.drawRenderedImage(src, at);
		ImageIO.write(dest, "JPG", new File(destFile));
	}

	/**
	 *  This method scales the image without keeping the original ratio of with and height
	 * @param src
	 * @param destWidth
	 * @param destHeight
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage scale(BufferedImage src, int destWidth, int destHeight) throws IOException {
		BufferedImage dest = new BufferedImage(destWidth, destHeight,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = dest.createGraphics();
		AffineTransform at = AffineTransform.getScaleInstance(
				(double) destWidth / src.getWidth(),
				(double) destHeight / src.getHeight());
		g.drawRenderedImage(src, at);
		return dest;
	}

	/**
	 * This method scales the image keeping the original ratio width/height
	 * @param src
	 * @param destWidth
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage scale(BufferedImage src, int destWidth) throws IOException {
		double ratio = (double)destWidth/(double)src.getWidth();
		double newHeight  = ratio * src.getHeight();
		int destHeight = (int) newHeight;
		BufferedImage dest = new BufferedImage(destWidth, destHeight,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = dest.createGraphics();
		AffineTransform at = AffineTransform.getScaleInstance(ratio, ratio);
		g.drawRenderedImage(src, at);
		return dest;
	}

}
